package edu.eece261.fall11;

import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.LinkedList;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;

import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ViewList extends Activity {
	
	public static final String PREFS_NAME = "SHOPPINGLISTLOGIN";
	
	ListDBAdapter listDBA;
	LinearLayout llSentences;
	Button bAddSentence;
	LinkedList<Long> timestampsGlobal;
	LinkedList<String> itemsGlobal;
	EditText etNewItem;
	EditText etEditItem;
	String title;
	int finished;
	int itemIndex = -1;

	Gson gson;
	Type collectionTypeString = new TypeToken<LinkedList<String>>() {
	}.getType();
	Type collectionTypeTimestamp = new TypeToken<LinkedList<Long>>() {
	}.getType();
	
	
	Intent results;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		title = getIntent().getStringExtra("list_title");
		this.setTitle(title);
		setContentView(R.layout.viewshoplist);

		if (title.equals("")) {
			results.putExtra("NULL", true);
			setResult(RESULT_CANCELED, results);
			finish();
		}
		
		llSentences = (LinearLayout) findViewById(R.id.llSentences);
		bAddSentence = (Button) findViewById(R.id.bAddSentence);
		
		listDBA = ListDBAdapter.getListDBAdapter(getApplicationContext());
		listDBA.open();

		gson = new Gson();

		fillData();
		
		bAddSentence.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(finished);
			}
		});
	}
	
	private void fillData() {
		llSentences.removeAllViews();
		Cursor story = listDBA.getEntryMatchingTitle(title);
		if (story.getCount() == 0) {
			results.putExtra("NULL", true);
			setResult(RESULT_CANCELED, results);
			finish();
		}
		
		story.moveToFirst();
		
		LinkedList<String> items = gson.fromJson(story
				.getString(ListDBAdapter.ITEMS_COLUMN), collectionTypeString);
		itemsGlobal = items;
		LinkedList<String> updaters = gson.fromJson(story
				.getString(ListDBAdapter.UPDATERS_COLUMN), collectionTypeString);
		LinkedList<Long> timestamps = gson.fromJson(story
				.getString(ListDBAdapter.TIMESTAMPS_COLUMN), collectionTypeTimestamp);
		timestampsGlobal = timestamps;
		for (int j = 0; j < timestamps.size(); ++j) {
			TextView currentSent = new TextView(this);
			currentSent.setText(items.get(j));
			currentSent.setTextSize(20);
			
			TextView currentUpdate = new TextView(this);
			String time = convertTime(timestamps.get(j));
			currentUpdate.setText(updaters.get(j) + " on " + time);
			currentUpdate.setTextSize(10);
			
			LinearLayout llSents = new LinearLayout(this);
			llSents.setOrientation(LinearLayout.VERTICAL);
			llSents.addView(currentSent, 0);
			llSents.addView(currentUpdate, 1);
			llSents.setId(j);
			
			llSents.setOnClickListener(new OnClickListener () {
				@Override
				public void onClick(View v) {
					itemIndex = v.getId();
					showDialog(-1000);
				}
			});
		
			llSentences.addView(llSents, j, new ViewGroup.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT));
		}
		
		finished = story.getInt(ListDBAdapter.FINISHED_COLUMN);
	}
	
	public String convertTime(long timestamp) {
		Calendar time = Calendar.getInstance();
		time.setTimeInMillis(timestamp);
		String month = "";
		switch(time.get(Calendar.MONTH)) {
		case Calendar.JANUARY:
			month = "Jan ";
			break;
		case Calendar.FEBRUARY:
			month = "Feb ";
			break;
		case Calendar.MARCH:
			month = "Mar ";
			break;
		case Calendar.APRIL:
			month = "Apr ";
			break;
		case Calendar.MAY:
			month = "May ";
			break;
		case Calendar.JUNE:
			month = "June ";
			break;
		case Calendar.JULY:
			month = "July ";
			break;
		case Calendar.AUGUST:
			month = "Aug ";
			break;
		case Calendar.SEPTEMBER:
			month = "Sept ";
			break;
		case Calendar.OCTOBER:
			month = "Oct ";
			break;
		case Calendar.NOVEMBER:
			month = "Nov ";
			break;
		case Calendar.DECEMBER:
			month = "Dec ";
		}
		
		String minute = "";
		if (time.get(Calendar.MINUTE) < 10) {
			minute = "0" + time.get(Calendar.MINUTE);
		} else {
			minute = time.get(Calendar.MINUTE) + "";
		}
			
		return month + time.get(Calendar.DAY_OF_MONTH) + ", " + time.get(Calendar.YEAR) + " at " + time.get(Calendar.HOUR) + ":" + minute;
	}
	
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		if (id == 0) {
			builder.setTitle("       Add Item       ").setView(
					etNewItem = new EditText(getApplicationContext())).setPositiveButton(
					"Add", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							if (etNewItem.getText().toString().equalsIgnoreCase("")) {
								makeToast("Item can't be blank.");
							} else {
								if (HTTPHelp.getActivityHTTPHelp().addItem(title, etNewItem.getText().toString(), getApplicationContext())) {
									makeToast("Item added successfully.");
									fillData();
									etNewItem.setText("");
								} else {
									makeToast("Item addition failed.");
									dialog.dismiss();
								}
							}
						}
					}).setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
						}
					});
		} else if (id == -1000) {
			etEditItem = new EditText(getApplicationContext());
			etEditItem.setText(itemsGlobal.get(itemIndex));
			builder.setTitle("      Edit Item       ").setView(etEditItem).setPositiveButton(
					"Save", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							if (etEditItem.getText().toString().equalsIgnoreCase("")) {
								makeToast("Item can't be blank.");
							} else {
								if (HTTPHelp.getActivityHTTPHelp().editItem(title, etEditItem.getText().toString(), timestampsGlobal.get(itemIndex),  getApplicationContext())) {
									dialog.dismiss();
									// TODO
									// This should be fillData() but the timestamp list is getting messed up
									finish();
									} else {
									makeToast("Item edit failed.");
									dialog.dismiss();
								}
							}
						}
					}).setNegativeButton("Delete",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							if (HTTPHelp.getActivityHTTPHelp().deleteItem(title, timestampsGlobal.get(itemIndex),  getApplicationContext())) {
								dialog.dismiss();
								// TODO
								// This should be fillData() but the timestamp list is getting messed up
								finish();
								makeToast("Item deleted successfully.");
							} else {
								makeToast("Item deletion failed.");
								dialog.dismiss();
							}
						}
						});
		} else {
			builder.setTitle("     Add Item     ").setMessage("Unable to add items to this list.").setNeutralButton("OK",
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.dismiss();
				}
			});
		}
		AlertDialog alert = builder.create();
		return alert;
	}

	void makeToast(String alert) {
		Toast.makeText(getApplicationContext(), alert, Toast.LENGTH_SHORT)
				.show();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		startService(new Intent(getApplicationContext(), ShoppingListService.class));
	}
	
	public void onPause() {
		super.onPause();
		stopService(new Intent(getApplicationContext(), ShoppingListService.class));
	}
}
